package org.mybatis.generator.plugins;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl;

import java.sql.Types;
import java.util.Properties;

/**
 * 自定义类型映射：
 * - DATE → LocalDate
 * - TIME → LocalTime
 * - DATETIME/TIMESTAMP → java.util.Date
 * - forceBigDecimals 可配置
 */
public class CustomJavaTypeResolver extends JavaTypeResolverDefaultImpl {

    private boolean forceBigDecimals = false;

    public CustomJavaTypeResolver() {
        super();
        this.useJSR310Types = false; // 禁用全局 JSR310 映射，我们手动控制
    }

    /**
     * 读取 generatorConfig.xml 中的 <property>
     */
    @Override
    public void addConfigurationProperties(Properties properties) {
        super.addConfigurationProperties(properties);
        String force = properties.getProperty("forceBigDecimals");
        if ("true".equalsIgnoreCase(force)) {
            this.forceBigDecimals = true;
        }
    }

    /**
     * 自定义 SQL 类型到 Java 类型的映射
     */
    @Override
    public FullyQualifiedJavaType calculateJavaType(IntrospectedColumn column) {
        int jdbcType = column.getJdbcType();

        switch (jdbcType) {
            case Types.INTEGER:
                return new FullyQualifiedJavaType("java.lang.Integer");
            case Types.BIGINT:
                return new FullyQualifiedJavaType("java.lang.Long");
            case Types.DECIMAL:
            case Types.NUMERIC:
                if (forceBigDecimals || column.getScale() > 0) {
                    return new FullyQualifiedJavaType("java.math.BigDecimal");
                } else {
                    // fallback，如果不希望它转 Long，可以统一转 BigDecimal
                    return new FullyQualifiedJavaType("java.lang.Long");
                }
            case Types.DATE:
                return new FullyQualifiedJavaType("java.time.LocalDate");
            case Types.TIME:
                return new FullyQualifiedJavaType("java.time.LocalTime");
            case Types.TIMESTAMP:
                return new FullyQualifiedJavaType("java.util.Date");
            default:
                return super.calculateJavaType(column);
        }
    }
}

